package com.example.demo.config.bigDecimalPattern;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

public class BigDecimalSerialize extends JsonSerializer<BigDecimal> implements ContextualSerializer {
    private String pattern;
    private int scale;
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else {
            if (StringUtils.isEmpty(pattern)) {
                String formattedValue =value.setScale(scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
                gen.writeNumber(new BigDecimal(formattedValue));
            } else {
                DecimalFormat decimalFormat = new DecimalFormat(pattern);
                String formattedValue = decimalFormat.format(value);
                gen.writeNumber(new BigDecimal(formattedValue));
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        //判断beanProperty是不是空
        if (property == null) {
            return prov.findNullValueSerializer(property);
        }
        //判断类型是否是BigDecimal
        if (Objects.equals(property.getType().getRawClass(), BigDecimal.class)) {
            JacksonBigDecimal annotation = property.getAnnotation(JacksonBigDecimal.class);
            if (annotation != null) {
                this.pattern =  annotation.pattern();
                this.scale =  annotation.scale();
                return this;
            }
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
